layui.use(['layer','jquery'],function(){
    var form = layui.form,
        element = layui.element;
    $ = layui.$;
    var layer = parent.layer === undefined ? layui.layer : top.layer;

    var request = GetRequest();

    //查询当前场景下的设备
    $.get("/equipment/query?sceneId=" + request.sceneId,function (data) {
        if (data.data.length != 0) {
            //加载当前场景下设备列表
            $("#barTypes").html("");
            $.each(data.data,function (i, ele) {
                if (i == 0) { //默认加载
                    $("#barTypes").append('<li class="active" data-value="'+ele.id+'">'+ele.name+'</li>');
                    init(ele.id);
                } else {
                    $("#barTypes").append('<li data-value="'+ele.id+'">'+ele.name+'</li>');
                }
            });
        } else {
            layer.msg("啊哦，找不到设备，切换场景试试？",{icon:5})
        }
    });

    /**
     * 初始化数据
     */
    function init(equipmentId) {
        if (equipmentId == null || equipmentId == "") {
            return;
        }

        //加载设备当前通道数据
        $.get("/equipment/channel/query?equipmentId=" + equipmentId,function (channel) {
            var checkItemLength = channel.count;
            if (checkItemLength == 0) {
                return null;
            }
            $("#check-item").html("");
            $.each(channel.data,function (i, ele) {
                if (i == 0) {
                    $("#check-item").append('<li class="layui-this" data-id="'+ ele.collectChannelApplicateTypeId +'">'+ ele.channelName +'</li>');
                    //加载当前通道的数据
                    initChart(equipmentId,ele.collectChannelApplicateTypeId);
                } else {
                    $("#check-item").append('<li class="" data-id="'+ ele.collectChannelApplicateTypeId +'">'+ ele.channelName +'</li>');
                }
            });

            //绑定事件，切换当前检测项目，刷新数据统计
            $("#check-item li").click(function () {
                var checkItemId = $(this).data("id");
                initChart(equipmentId,checkItemId);
            });
        });

        /**
         * 初始化统计图
         * @param equipmentId
         * @param checkItemId
         */
        function initChart(equipmentId,checkItemId) {
            var searchObj = {};
            searchObj.page = 0;
            searchObj.limit = 100;//设置默认最大查询范围
            searchObj.equipmentId = equipmentId;
            searchObj.checkItemId = checkItemId;

            $.get("/search/datarecord/page/query?",searchObj,function (data) {
                //当前设备的检测项目
                if (data.data.length <= 0) {
                    //关闭加载动画
                    $("#echart-show").html('<div align="center">没有与之匹配的数据</div>')
                }
                $("#echart-show").html("");
                //x轴时间组件
                var xAxisdataArr = [];
                var seriesArr = [];
                var checkMessage = {};
                $.each(data.data,function (j, ele) {
                    var date = new Date(ele.acquisitionTime);
                    var dateStr = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
                    xAxisdataArr.unshift(dateStr);
                    seriesArr.unshift(ele.processedData);
                    checkMessage.title = ele.checkItemName + "趋势";
                    checkMessage.legendData = ele.checkItemName;
                    checkMessage.seriesName = ele.checkItemName;
                    checkMessage.yAxisformatter = ele.unit;
                });
                setTrendData(checkItemId,xAxisdataArr,seriesArr,checkMessage);
            });

        }

        /**
         * 设置检测项目相应的数据统计
         * @param checkItemId
         * @param xAxisdataArr
         * @param seriesArr
         * @param checkMessage
         */
        function setTrendData(checkItemId,xAxisdataArr, seriesArr, checkMessage) {
            //折线图
            var lineChart = echarts.init(document.getElementById('linechart'));
            var option = {
                title: {
                    text: checkMessage.title,
                    subtext: ' '
                },
                tooltip: {
                    trigger: 'axis'
                },
                color:"#0f9ac3",
                legend: {
                    data:[checkMessage.legendData]
                },
                toolbox: {
                    show: true,
                    feature: {
                        dataZoom: {
                            yAxisIndex: 'none'
                        },
                        dataView: {readOnly: false},
                        magicType: {type: ['line', 'bar']},
                        restore: {},
                        saveAsImage: {}
                    }
                },
                dataZoom: {
                    show: true,
                    realtime : true,
                    start: 0,
                    end: 18,
                    height: 20,
                    backgroundColor: '#f8f8f8',
                    dataBackgroundColor: '#e4e4e4',
                    fillerColor: '#87cefa',
                    handleColor: '#87cefa',
                },
                xAxis:  {
                    type: 'category',
                    boundaryGap: false,
                    data: xAxisdataArr
                },
                yAxis: {
                    type: 'value',
                    axisLabel: {
                        formatter: '{value} ' + checkMessage.yAxisformatter
                    }
                },
                series: [
                    {
                        name:checkMessage.seriesName,
                        type:'line',
                        data:seriesArr,
                        markPoint: {
                            data: [
                                {type: 'max', name: '最大值'},
                                {type: 'min', name: '最小值'}
                            ]
                        },
                        markLine: {
                            data: [
                                {type: 'average', name: '平均值'}
                            ]
                        },
                        lineStyle: {
                            normal: {
                                color:"#0f9ac3"
                            }
                        }
                    }
                ]
            };
            lineChart.setOption(option);
        }
    }

    /**
     * 获取路径中的参数
     * @returns {Object}
     * @constructor
     */
    function GetRequest() {
        var url = location.search;         //获取url中"?"符后的字串
        var theRequest = new Object();
        if (url.indexOf("?") != -1) {
            var str = url.substr(1);
            var strs = str.split("&");
            for (var i = 0; i < strs.length; i++) {
                theRequest[strs[i].split("=")[0]] = decodeURIComponent(strs[i].split("=")[1]);
            }
        }
        return theRequest;
    }


    /**
     * 判断数组中是否存在元素
     * @param arr
     * @param obj
     * @returns {number}
     */
    function contains(arr, obj) {
        if (arr.length != 0) {
            for (var i = 0;i < arr.length;i++) {
                if(arr[i] == obj) {
                    return -1;
                }
            }
        }
        return 0;
    }

    /**
     * 获取当前时间，以solr中date的格式 2018-08-27T02:28:58Z
     * @param date
     * @returns {string}
     */
    function getSolrDate(date) {
        var year = date.getFullYear();
        var month = (date.getMonth() + 1) >= 10 ? (date.getMonth() + 1) : "0" + (date.getMonth() + 1);
        var day = date.getDate() >= 10 ? date.getDate() : "0" + date.getDate();
        var hour = date.getHours() >= 10 ? date.getHours() : "0" + date.getHours();
        var minutes = date.getMinutes() >= 10 ? date.getMinutes() : "0" + date.getMinutes();
        var seconds = date.getSeconds() >= 10 ? date.getSeconds() : "0" + date.getSeconds();
        var dateStr = year + '-' + month + '-' + day + 'T' + hour + ':' + minutes + ':' + seconds + 'Z';
        return dateStr;
    }


});